//package com.sunop.pantiai.controller;
//
//import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
//import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisAudioFormat;
//import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
//import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
//import com.alibaba.dashscope.common.ResultCallback;
//import com.alibaba.dashscope.exception.NoApiKeyException;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
//
//import java.io.OutputStream;
//import java.nio.ByteBuffer;
//import java.time.LocalDateTime;
//import java.time.format.DateTimeFormatter;
//import java.util.concurrent.CountDownLatch;
//import java.util.concurrent.atomic.AtomicBoolean;
//
///**
// * TTS Controller
// * 额度用完了，弃用
// * 功能是可以的
// */
//@RestController
//@RequestMapping("/api/tts")
//public class TTSController {
//
//    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
//    private static final String model = "cosyvoice-v1";
//    private static final String voice = "longxiaochun";
//
//    private String getTimestamp() {
//        return LocalDateTime.now().format(formatter);
//    }
//
//    @GetMapping(value = "/stream", produces = "audio/mpeg")
//    public ResponseEntity<StreamingResponseBody> streamAudioData(@RequestParam(required = false, defaultValue = "今天天气怎么样？") String text) throws NoApiKeyException {
//        return ResponseEntity
//                .ok()
//                .contentType(MediaType.parseMediaType("audio/mpeg"))
//                .header(HttpHeaders.CONTENT_DISPOSITION, "inline")
//                .body(outputStream -> {
//                    try {
//                        streamAudioToOutputStream(outputStream, text);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                });
//    }
//
//    private void streamAudioToOutputStream(OutputStream outputStream, String text) throws Exception {
//        CountDownLatch latch = new CountDownLatch(1);
//        AtomicBoolean hasError = new AtomicBoolean(false);
//
//        // 实现回调接口ResultCallback
//        ResultCallback<SpeechSynthesisResult> callback = new ResultCallback<SpeechSynthesisResult>() {
//            @Override
//            public void onEvent(SpeechSynthesisResult result) {
//                try {
//                    if (result.getAudioFrame() != null) {
//                        ByteBuffer buffer = result.getAudioFrame();
//                        byte[] bytes = new byte[buffer.remaining()];
//                        buffer.get(bytes);
//
//                        // 将数据写入输出流
//                        outputStream.write(bytes);
//                        outputStream.flush();
//
//                        System.out.println(getTimestamp() + " 发送音频数据: " + bytes.length + " 字节");
//                    }
//                } catch (Exception e) {
//                    System.out.println("处理音频帧时出错: " + e.getMessage());
//                    hasError.set(true);
//                    latch.countDown();
//                }
//            }
//
//            @Override
//            public void onComplete() {
//                System.out.println(getTimestamp() + " 音频合成完成");
//                latch.countDown();
//            }
//
//            @Override
//            public void onError(Exception e) {
//                System.out.println("音频合成错误: " + e.toString());
//                hasError.set(true);
//                latch.countDown();
//            }
//        };
//
//        SpeechSynthesisParam param = SpeechSynthesisParam.builder()
//                .apiKey("sk-766d19a835b94bb0b8778b2f7d00dea3") // 设置API Key
//                .model(model)
//                .voice(voice)
//                .format(SpeechSynthesisAudioFormat.MP3_16000HZ_MONO_128KBPS) // 使用MP3格式，更兼容浏览器
//                .build();
//
//        // 第二个参数传入回调即启用异步模式
//        SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, callback);
//
//        // 发送合成请求
//        synthesizer.call(text);
//
//        // 等待合成完成
//        latch.await();
//
//        System.out.println(
//                "[指标] 请求ID: " + synthesizer.getLastRequestId() +
//                        ", 首包延迟毫秒: " + synthesizer.getFirstPackageDelay());
//
//        if (hasError.get()) {
//            throw new Exception("音频合成过程中发生错误");
//        }
//    }
//
//    @GetMapping("/test")
//    public String test() {
//        return "TTS Controller is working!";
//    }
//}